﻿// Author: Miroslav Matula m.matula@alutam.cz 
// Date : 31/8/2010
namespace System.Windows.Controls
{
	public class DataGridToolBarRIA : DataGridToolBarBase
	{
    public DataGridToolBarRIA()
    {
      ButtonRefreshVisible = true;
    }

    #region -- DomainDataSource ----------------------------
		/// <summary>
		/// Reference to DomainDataSource.
		/// </summary>
    /// <example>XAML
    /// <code>
    /// DomainDataSource="{ Binding ElementName=domainDataSourceNameControl, Mode=OneTime}"
    /// </code>
    /// </example>
    public DomainDataSource DomainDataSource
		{
			get { return (DomainDataSource)GetValue(DomainDataSourceProperty); }
			set { SetValue(DomainDataSourceProperty, value); }
		}

		public static readonly DependencyProperty DomainDataSourceProperty =
				DependencyProperty.Register("DomainDataSource", typeof(DomainDataSource), typeof(DataGridToolBarRIA), new PropertyMetadata(null, new PropertyChangedCallback(OnDomainDataSourceChanged)));

		private static void OnDomainDataSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			if(e.OldValue != null) ((DataGridToolBarRIA)d).DetachDomainDataSource((DomainDataSource)e.OldValue);
			((DataGridToolBarRIA)d).AttachDomainDataSource((DomainDataSource)e.NewValue);
		}

		private void DetachDomainDataSource(DomainDataSource domain_)
		{
      domain_.LoadedData -= new EventHandler<LoadedDataEventArgs>(domain__LoadedData);
      this.ClearValue(IsBusyProperty); // has binding to DomainSource
      this.ClearValue(CanLoadProperty);// has binding to DomainSource
		}
		//-------
		private void AttachDomainDataSource(DomainDataSource domain_)
		{
			this.SetBinding(IsBusyProperty, new Data.Binding("IsBusy") { Source = domain_ });
			this.SetBinding(CanLoadProperty, new Data.Binding("CanLoad") { Source = domain_ });
      //domain_.SubmittedChanges += new EventHandler<SubmittedChangesEventArgs>(domain__SubmittedChanges); this not works
      domain_.LoadedData += new EventHandler<LoadedDataEventArgs>(domain__LoadedData);
			IsHitTestVisible = DataGrid != null;
		}

    void domain__LoadedData(object sender, LoadedDataEventArgs e)
    {
      if(e.Cancelled) SetMessageCancelled();
      else if(e.HasError)SetMessageError(e.Error.Message);
    }

		//-------

		#endregion

    public override bool IsLoading { get { return DomainDataSource.DomainContext.IsLoading; } }

    public override bool IsSubmitting { get { return DomainDataSource.DomainContext.IsSubmitting; } }

    //------------------
		override public void ApplyFiltr()
		{
			if(DomainDataSource == null) return;

			FilterMessage.Inlines.Clear();
			using(DomainDataSource.DeferLoad()) {
				DomainDataSource.FilterDescriptors.Clear();
				DomainDataSource.FilterOperator = FilterDescriptorLogicalOperator.And;
				//todu:pozor EntityContainer.Clear(); - vymazat jen entity set
				DomainDataSource.DomainContext.EntityContainer.Clear();  // DomainContext.EntityContainer.

				bool firstItem = true;
				foreach(var item in Filter) {
					var fd = new FilterDescriptor(item.ColumnName, (FilterOperator)item.Operator, item.Value);
					DomainDataSource.FilterDescriptors.Add(fd);

					if(!firstItem) FilterMessage.Inlines.Add(new Documents.Run() { Text = " " +  LangResources.LocalizedStrings.DGTB_and + " " }); 
					FilterMessage.Inlines.Add(new Documents.Run() { Text = item.Title });
					FilterMessage.Inlines.Add(new Documents.Run() { Text = " " + item.Mark + " ", Foreground = MessageOperatorBrush });
					FilterMessage.Inlines.Add(new Documents.Run() { Text = item.Value, FontWeight = FontWeights.Black }); 
					firstItem = false;
				}
			}
			OnFilter(new HandledEventArgs());
		}
		//---------------------
		public override bool DataHasChanges {
			get {
				return (DomainDataSource!=null && DomainDataSource.HasChanges);
			}
		}
		//---------------------
    private System.ServiceModel.DomainServices.Client.SubmitOperation _submitOperation;
    public override void OnSubmitChanges(HandledEventArgs arg)
    {
      if(IsBusyCnt > 0) throw new Exception("It can't SaveChanges. IsBusy == true  ");
      base.OnSubmitChanges(arg);
      if(!arg.Handled) {
        _submitOperation = DomainDataSource.DomainContext.SubmitChanges((p) => {
          this.Dispatcher.BeginInvoke(() => {
            if(_submitOperation==p) _submitOperation = null;
            if(DataFormWindow != null && ((System.Windows.Controls.Primitives.Popup)DataFormWindow.Parent).IsOpen) {
              IDataGridToolBar_DataFormWindow mw = DataFormWindow as IDataGridToolBar_DataFormWindow;
              if(mw.CallBackDataChanged != null) {
                bool ok = !p.IsCanceled && !p.HasError;
                mw.CallBackDataChanged(ok);
              }
            }
            IsBusyCnt--;
            if(p.HasError) {
              // reakce na chyby
              SetMessageError(p.Error.Message);
            }
            if(p.IsCanceled) {
              SetMessageCancelled();
            }
          });
        }, null);
        IsBusyCnt++;
      }
		}
    //---------------------
    public override void OnCancelLoadOrSubmitChanges()
    {
      if(DomainDataSource.DomainContext.IsLoading) {
        DomainDataSource.CancelLoad();
        DomainDataSource.Clear();
      } if(DomainDataSource.DomainContext.IsSubmitting) {
        if(_submitOperation != null && _submitOperation.CanCancel) {
          _submitOperation.Cancel();
          DomainDataSource.Clear();
        }
      }
      base.OnCancelLoadOrSubmitChanges();
    }
    //---------------------
		public override void OnRefreshData(HandledEventArgs arg)
		{
			base.OnRefreshData(arg);
			if(!arg.Handled) {
				this.DomainDataSource.Clear();
				DomainDataSource.Load(); //
			}
		}
		//---------------------
		public override void OnRejectChanges(HandledEventArgs arg)
		{
			base.OnRejectChanges(arg);
			if(!arg.Handled) {
				if(this.DomainDataSource.IsSubmittingChanges) this.DomainDataSource.CancelSubmit();
				this.DomainDataSource.DomainContext.RejectChanges();
			}
		}
		//---------------------
		protected override void AttachDataGrid(DataGrid dg_)
		{
			base.AttachDataGrid(dg_);
			IsHitTestVisible = DomainDataSource != null;
		}


	}
}
